<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>列表拖拽</title>
    <style>
      ul > li {
        list-style: none;
        padding: 10px;
        background-color: #f0f0f0;
        margin-bottom: 10px;
        cursor: pointer;
        transition: transform 0.3s ease;
      }
    </style>
  </head>
  <body>
    <div id="app">
      具体想要的效果还是看vue的拖拽组件吧，这里只是简单的实现拖拽
      <ul id="list">
        <li draggable="true" data-id="1">A</li>
        <li draggable="true" data-id="2">B</li>
        <li draggable="true" data-id="3">C</li>
        <li draggable="true" data-id="4">D</li>
        <li draggable="true" data-id="5">E</li>
      </ul>
    </div>

    <div>
      <button @click="">点击触发</button>
    </div>

    <script>
      const list = document.getElementById('list')
      let dragIndex = -1

      list.addEventListener('dragstart', e => {
        if (e.target.tagName === 'LI') {
          dragIndex = Array.from(list.children).indexOf(e.target)
          // 禁用过渡效果
          Array.from(list.children).forEach(item => {
            item.style.transition = 'none'
          })
        }
      })

      list.addEventListener('dragover', e => {
        e.preventDefault()
        if (e.target.tagName === 'LI') {
          const dragOverIndex = Array.from(list.children).indexOf(e.target)
          if (dragIndex !== dragOverIndex) {
            const dragItem = list.children[dragIndex]
            const targetItem = list.children[dragOverIndex]
            list.insertBefore(
              dragItem,
              dragOverIndex > dragIndex ? targetItem.nextSibling : targetItem
            )
            dragIndex = dragOverIndex
          }
        }
      })

      list.addEventListener('drop', () => {
        // 恢复过渡效果
        Array.from(list.children).forEach(item => {
          item.style.transition = 'transform 0.3s ease'
        })
        // 将元素的位置重置为原始位置
        Array.from(list.children).forEach((item, index) => {
          item.style.transform = `translateY(${index}px)`
        })
      })
    </script>
  </body>
</html>
